<?php


namespace app\base\service;

use app\base\model\MemberBeanPackages;
use app\base\model\MemberDevicePackages;
use app\base\model\MemberOrder as MemberOrderMod;
use app\base\model\MemberPlans;
use app\wechat\service\MediaService;
use think\admin\Exception;
use think\admin\extend\CodeExtend;
use think\admin\service\AdminService;
use app\base\model\MemberOrder;
use think\Response;

/**
 * 会员相关服务
 * Class AdminService
 * @package think\admin\service
 */
class MemberService extends AdminService
{
    //创建订单
    public function createOrder($user_id,$package_id,$num,$type,$create_type=1) {
        $order_no =  CodeExtend::uniqidDate(18, 'NO');
        $order = [
            'order_no'=>$order_no,
            'user_id'=>$user_id,
            'type'=>$type,
            'num'=>$num,
            'package_id'=>$package_id,
            'status'=>1,
        ];
        if($type==1){
            $package = MemberPlans::mQuery()->where(['id'=>$package_id])->find();
            if(empty($package)) $this->error('套餐不存在');
            $order['price'] = $package['price'];
            $order['amount'] = $package['price']*$num;
            $order['title'] = $package['version_type'];
            $order['remark'] = $package['version_type']."-".$package['specification'];
            $order['yh_amount'] = ($package['hx_price']*$num)-$order['amount'];
        }else if ($type==2){
            $package = MemberBeanPackages::mQuery()->where(['id'=>$package_id])->find();
            if(empty($package)) $this->error('套餐不存在');
            $order['price'] = $package['price'];
            $order['amount'] = $package['price']*$num;
            $order['yh_amount'] = ($package['hx_price']*$num)-$order['amount'];
            $order['title'] = "蓝豆加量包";
            $order['remark'] = "基础蓝豆：".$package['base_beans'];
            if($package['bonus_beans']!=0){
                $order['remark'] .= "+加赠蓝豆：".$package['bonus_beans'];
                $order['remark'] = $order['remark']."合计：".($package['base_beans']+$package['bonus_beans'])."蓝豆";
            }
        }else{
            $package = MemberDevicePackages::mQuery()->where(['id'=>$package_id])->find();
            if(empty($package)) $this->error('套餐不存在');
            $order['price'] = $package['price'];
            $order['amount'] = $package['price']*$num;
            $order['yh_amount'] = ($package['hx_price']*$num)-$order['amount'];
            switch ($type){
                case 3:
                    $order['title'] = "设备加量包";
                    $order['remark'] = "设备数量:".$package['numbers']*$num."台";
                    break;
                case 4:
                    $order['title'] = "音频模板加量包";
                    $order['remark'] = "音频模板数量:".$package['numbers']*$num."个";
                    break;
                case 5:
                    $order['title'] = "视频模板加量包";
                    $order['remark'] = "视频模板数量:".$package['numbers']*$num."个";
                    break;
            }
        }
        $order['content'] = json_encode($package);
        $order['create_type'] = $create_type;
        if($create_type==2){
            $order['status'] = 2;
        }
        $order_id = MemberOrderMod::mQuery()->insertGetId($order);
        return  $order_id;
    }

    //创建微信支付
    public function createWxPay($order_id,$pay_type="wechat_qrc") {
        $order = MemberOrderMod::mQuery()->where(['id'=>$order_id])->find();
        if(empty($order)) return  ['code'=>0,'info'=>'订单不存在'];
        try {
            $r = PaymentService::create(
                $order['user_id'],
                $order['order_no'],
                $order['title'],
                $order['amount'],
                $pay_type,
                $order['amount'],
                $order['remark']);
            if($r['code']==1){
                $code_url = $r['params']['code_url'];
                $ewm_url = $this->_buildQrcResponse($code_url);
                $order['ewm_url'] = $ewm_url;
                return ['code'=>1,'info'=>'创建微信支付成功','data'=>$order];
            }else{
                return ['code'=>0,'info'=>$r['info']];
            }
        } catch (Exception $e) {
            $this->app->log->error("创建微信支付失败：".$e->getMessage());
            return ['code'=>0,'info'=>"创建微信支付失败：".$e->getMessage()];
        }
    }
    /**
     * 创建二维码响应对应
     * @param string $url 二维码内容
     * @return String
     */
    private function _buildQrcResponse(string $url)
    {
        $result = MediaService::getQrcode($url);


        return $result->getDataUri();
    }

    //已支付订单内容发放
    public function payOrderContent($order_id) {
        $order = MemberOrder::mQuery()->where(['id'=>$order_id])->find();
        if(empty($order)) return false;
        if($order['status']!=2) return false;
        if($order['is_use']==1) return false;
        $content = json_decode($order['content'],true);
        if(empty($content)) return false;
        $this->app->db->startTrans();
        try{
            if($order['type']==1){
                //发放基础套餐内容
                //计算有效期(几个月)
                $duration = $order['num']*$content['duration'];
                //查询当前用户期限
                $now_expire_date = $this->app->db->name("ai_user")->where(['id'=>$order['user_id']])->value("expire_date");
                if (strtotime($now_expire_date) < time()) {
                    // 当前已过期：从当前时间开始计算
                    $expire_date = date('Y-m-d', strtotime("+{$duration} months"));
               } else {
                    // 未过期：在现有有效期基础上延长
                    $expire_date = date('Y-m-d', strtotime("{$now_expire_date} +{$duration} months"));
                }
                //发放蓝豆 (按月发放,第一次开通或者会员已过期重新开通,按照一个月为一周期发放,当前发放一次)
                $this->issueBeans($order['user_id'], $content['id'], $content['beans'], $expire_date, $order_id,$order['type'],$order['create_type']);

                // 更新用户有效期
                $this->app->db->name("ai_user")
                    ->where(['id' => $order['user_id']])
                    ->update(['expire_date' => $expire_date,
                        'member_plans_id'=>$content['id'],
                        'jc_devices'=>$content['devices'],
                        'js_voices'=>$content['voices'],
                        'js_videos'=>$content['videos'],
                        ]);



            }elseif($order['type']==2){
                //发放加量套餐内容
                $duration = $order['num']*$content['duration'];
                $this->issueBeans($order['user_id'], $content['id'], $content['base_beans']+$content['bonus_beans'], $duration, $order_id,$order['type'],$order['create_type']);
            }else{
                //发放设备套餐内容
                switch ($order['type']){
                    case 3:
                        $this->app->db->name("ai_user")->where(['id'=>$order['user_id']])->inc("jl_devices",$content['numbers']*$order['num'])->update();
                        break;
                    case 4:
                        $this->app->db->name("ai_user")->where(['id'=>$order['user_id']])->inc("jl_voices",$content['numbers']*$order['num'])->update();
                        break;
                    case 5:
                        $this->app->db->name("ai_user")->where(['id'=>$order['user_id']])->inc("jl_videos",$content['numbers']*$order['num'])->update();
                        break;
                }

            }
            // 标记订单已使用
            MemberOrder::mk()->where(['id' => $order_id])->update([
                'is_use' => 1,
            ]);
            $this->app->db->commit();
            return true;
        }catch (\Exception $e){
            $this->app->db->rollback();
            $this->app->log->error("已支付订单内容发放失败：".$e->getMessage());
            return false;
        }
    }

    /**
     * 发放蓝豆
     */
    private function issueBeans($user_id, $package_id, $beans, $duration, $order_id,$duration_type=1,$create_type=1)
    {
        $current_time = time();
        if($duration_type==1){
            //基础套餐
            $expire_date = $duration;
            //$expire_date = date('Y-m-d', strtotime("+{$duration} months"));
        }else{
            $expire_date = date('Y-m-d', strtotime("+{$duration} days"));
        }
        //$expire_time = strtotime("+{$duration} months", $current_time);

        $this->app->db->name('member_bean_records')->insert([
            'user_id' => $user_id,
            'package_id' => $package_id,
            'source_type' => $duration_type,
            'total_beans' => $beans,
            'remaining_beans' => $beans,
            'expire_date' => $expire_date,
            'order_id' => $order_id,
            'create_type'=>$create_type
        ]);
    }

    //定时发放蓝豆
    public function cronIssueBeans()
    {
        //查询所有未过期的用户
        $users = $this->app->db->name('ai_user')
            ->whereTime('expire_date', '>', date('Y-m-d'))
            ->select()->toArray();
        foreach ($users as $user) {
            //判断当前周期是否已发放
            //发放周期(月)
            $duration = $user['duration'];
            // 获取用户最新的蓝豆记录
            $latestRecord = $this->app->db->name('member_bean_records')
                ->where(['user_id'=>$user['id'],'source_type'=>1])
                ->order('id', 'desc')
                ->find();
            // 判断是否需要发放
            $shouldIssue = false;
            if (empty($latestRecord)) {
                // 如果没有记录，需要发放
                $shouldIssue = true;
            } else {
                // 如果有记录，检查是否到达下一个发放周期
                $lastIssueDate = strtotime($latestRecord['create_at']);
                $nextIssueDate = strtotime("+$duration months", $lastIssueDate);
                if (time() >= $nextIssueDate) {
                    $shouldIssue = true;
                }
            }

            if ($shouldIssue) {
                // 确定发放的蓝豆数量（这里假设每次发放固定数量的蓝豆，实际可以根据业务逻辑调整）
                $beansToIssue = $this->app->db->name('member_plans')->where('id', $user['member_plans_id'])->value("beans"); // 示例值，实际应根据业务规则确定

                // 计算过期日期
                $expireDate = date('Y-m-d', strtotime("+$duration months"));

                // 插入新的蓝豆记录
                $this->app->db->name('member_bean_records')->insert([
                    'user_id' => $user['id'],
                    'package_id' => $user['member_plans_id'],
                    'source_type' => 1,
                    'total_beans' => $beansToIssue,
                    'remaining_beans' => $beansToIssue,
                    'expire_date' => $expireDate,
                    'order_id' => null, // 定时任务发放，没有对应的订单
                ]);
            }
        }
    }

    // 使用时优先使用最早即将过期的蓝豆
    public function useBeans($user_id, $amount)
    {
        // 先检查总可用蓝豆是否充足
        $totalAvailable = $this->app->db->name('member_bean_records')
            ->where('user_id', $user_id)
            ->where('remaining_beans', '>', 0)
            ->sum('remaining_beans');

        if ($totalAvailable < $amount) {
            // 抛出异常或返回错误码（根据业务需求选择）
            return 0;
            // 或 return false;
        }
        $record_id = [];
        $records = $this->app->db->name('member_bean_records')
            ->where('user_id', $user_id)
            ->where('remaining_beans', '>', 0)
            ->order('expire_date ASC')
            ->select();

        foreach ($records as $record) {
            if ($amount <= 0) break;

            $usable = min($record['remaining_beans'], $amount);

            $this->app->db->name('member_bean_records')
                ->where('id', $record['id'])
                ->inc('used_beans', $usable)
                ->dec('remaining_beans', $usable)
                ->update();

            $amount -= $usable;
            $record_id[]=$record['id'];
        }


        return $record_id;
    }

    // 获取用户剩余蓝豆数量
    public function getUserRemainingBeans($user_id){
        //return 10;
        $remainingBeans = $this->app->db->name('member_bean_records')
            ->whereTime('expire_date', '>', date('Y-m-d'))
            ->where('user_id', $user_id)
            ->where('remaining_beans', '>', 0)
            ->sum('remaining_beans');

        return $remainingBeans;
    }

    //计费逻辑
    public function charge($user_id, $stage_tag,$data,$platform=""){
        //return ['code'=>1,'msg'=>"成功"];
       if( $this->getUserRemainingBeans($user_id)<2){
           return ['code'=>0,'msg'=>"蓝豆不足"];
       }
       $this->app->db->startTrans();
       try{
           //查询计费规则
           $where  = [
               'stage_tag'=>$stage_tag,
           ];
           if($platform){
               $where['platform'] = $platform;
           }
           $pricing_rules = $this->app->db->name("member_pricing_rules")->where($where)->find();
           $remark = "";
          // $this->app->log->error("计费参数：".json_encode($where));
          // $this->app->log->error("计费规则：".json_encode($pricing_rules));
           switch ($pricing_rules['stage_tag']){
               case "ByRdGather":
                   $amount = $pricing_rules['price_per_unit'];
                   $remark = "热点采集消耗蓝豆：".$amount;
                   break;
               case "AccountGatherDy":
                   //抖音账号采集
                   $amount = $pricing_rules['price_per_unit'];
                   $remark = $pricing_rules['stage']."消耗蓝豆：".$amount;
                   break;
               case "VideoToText":
                   //视频转文本
                   list($minutes, $seconds) = explode(':', $data['share_duration']);
                   $totalSeconds = (int)$minutes * 60 + (int)$seconds;
                   $amount = ceil($totalSeconds/$pricing_rules['unit_number']) * $pricing_rules['price_per_unit'];
                   $remark = $pricing_rules['stage']."消耗蓝豆：".$amount;
                   break;
               case "textGenerate":
                   //文本生成
                   $ai_gaixie_content = $data['ai_gaixie_content'];
                   $ai_gaixie_content_length = mb_strlen($ai_gaixie_content);
                   $amount = ceil(($ai_gaixie_content_length/$pricing_rules['unit_number']) * $pricing_rules['price_per_unit']);
                   $remark = "AI改写字数：".$ai_gaixie_content_length."字，消耗蓝豆：".$amount;
                   break;
               case "voiceGenerate":
                   //音频生成
                   $audio_duration = $data['audio_duration'];
                   if($pricing_rules['unit_description']=="分钟"){
                       $audio_duration = ceil(($audio_duration/60)*100)/100;
                   }
                   $amount = ceil($audio_duration/$pricing_rules['unit_number']) * $pricing_rules['price_per_unit'];
                   $remark = "【{$pricing_rules['stage']}】生成音频时长：".$audio_duration."{$pricing_rules['unit_description']}，消耗蓝豆：".$amount;
                   break;
               case "voiceGenerateV2":
                   //音频生成
                   $audio_duration = $data['audio_duration'];
                   if($pricing_rules['unit_description']=="分钟"){
                       $audio_duration = ceil(($audio_duration/60)*100)/100;
                   }
                   $amount = ceil($audio_duration/$pricing_rules['unit_number']) * $pricing_rules['price_per_unit'];
                   $remark = "【{$pricing_rules['stage']}】生成音频时长：".$audio_duration."{$pricing_rules['unit_description']}，消耗蓝豆：".$amount;
                   break;
               case "videoGenerate":
                   //视频生成
                   $video_duration = $data['video_duration'];
                   if($pricing_rules['unit_description']=="分钟"){
                       $video_duration =ceil(($video_duration/60)*100)/100;
                   }
                   $amount = ceil($video_duration/$pricing_rules['unit_number']) * $pricing_rules['price_per_unit'];
                   $remark = "生成视频时长：".$video_duration."{$pricing_rules['unit_description']}，消耗蓝豆：".$amount;
                   break;
               case "UrlVideoToText":
                   //分享链接提取视频文本
                   $content = $data['content'];
                   $content_length = mb_strlen($content);
                   $amount = ceil($content_length/$pricing_rules['unit_number']) * $pricing_rules['price_per_unit'];
                   $remark = "分享链接提取视频文案字数：".$content_length."字，消耗蓝豆：".$amount;
                   break;
               case "voiceTemplate":
                   //音频模板生成
                   $amount = $pricing_rules['price_per_unit'];
                   $remark = "音频模板生成消耗蓝豆：".$amount;
                   break;
               case "videoTemplate":
                   //视频模板生成
                   $amount = $pricing_rules['price_per_unit'];
                   $remark = "视频模板生成消耗蓝豆：".$amount;
                   break;
           }
           if($amount>0){
               $this->app->log->error("用户".$user_id."开始计费：".$amount);
               $r = $this->useBeans($user_id,$amount);
               if ($r==0){
                   $this->app->db->rollback();
                   return ['code'=>0,'msg'=>"蓝豆不足"];
               }
               $consumption_records = [
                   'user_id' => $user_id,
                   'stage_tag' => $stage_tag,
                   'beans_used' => $amount,
                   'record_id' => implode(',',$r),
                   'content' => json_encode($data),
                   'remark'=>$remark
               ];
               $this->app->db->name('member_consumption_records')->insert($consumption_records);
               $this->app->db->commit();
               return ['code'=>1,'msg'=>"成功"];
           }else{
               $this->app->db->commit();
               return ['code'=>1,'msg'=>"成功"];
           }
       }catch (\Exception $e){
           $this->app->db->rollback();
           $this->app->log->error("蓝豆扣除失败：".$e->getMessage());
           return ['code'=>0,'msg'=>$e->getMessage()];
       }

    }

}
